package com.tour.silvertour.Controller;

import com.alibaba.fastjson2.JSON;
import com.tour.silvertour.Common.Utils.R;
import com.tour.silvertour.Common.Utils.SecurityUtils;
import com.tour.silvertour.Entity.User;
import com.tour.silvertour.Service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Title: UserController
 * @Author 苗桐菲
 * @Package com.tour.silvertour.Controller
 * @Date 2024/3/30 20:29
 */
@Controller
@RequestMapping("/api/user")
public class UserController extends BaseController{

    @Autowired
    private IUserService userService;
    @Autowired
    private RedisTemplate redisTemplate;


    /*
    * 登陆功能
    * */
    @PostMapping("/login")
    public R login(@RequestBody User suser) {

        User user = userService.selectUserByUserName(suser.getUserName());
        System.out.println(user);
        if (user == null) {
            return R.error(404, "用户不存在");
        }
        boolean ok = SecurityUtils.matchesPassword(suser.getPassword(), user.getPassword());
//         boolean ok=false;
//        if(suser.getPassword()==user.getPassword())
//        {
//            ok=true;
//            System.out.println("yes");
//        }
//        if (suser.getPassword() == null || suser.getPassword().isEmpty()) {
//            return R.error(400, "密码不能为空");
//        }

        if (!ok) {
            System.out.println("no");
            return R.error(404, "账号密码错误");
        }
        String token = UUID.randomUUID().toString().replace("-", "");
        System.out.println(token);
        String jsonStr = JSON.toJSONString(user);
        redisTemplate.opsForValue().set(token, jsonStr, 1, TimeUnit.HOURS);
        return R.success().put("token", token);
    }
    /*
    * 注册功能
    * */
    @PostMapping("/register")
    public R register(@RequestBody User user){
        userService.register(user);
        return R.success("注册成功");
    }
    @GetMapping("/get")
    public R getUser(HttpServletRequest request) {
        String token = request.getHeader("token");
        String user = (String) redisTemplate.opsForValue().get(token);
        User sUser = JSON.parseObject(user, User.class);
        return R.success(sUser);
    }
}
